/*###################################################################
  > File Name: cbb/src/cleanup_offline_msg.c
  > Author: Vurtune
  > Mail: vurtune@foxmail.com
  > Created Time: Fri 03 Nov 2017 01:09:29 AM PDT
###################################################################*/
#include "config.h"

#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

#define DBG_SUBSYS S_LIBINTERFACE

#include "lich_md.h"
#include "hostmap.h"
#include "etcd.h"

int offline_msg_create(const nid_t *nid, volid_t *volid)
{
        int ret;
        char etcdpath[MAX_NAME_LEN], idstr[MAX_NAME_LEN];

        sprintf(etcdpath, "%s/%d", ETCD_CLEANUP, nid->id);
        ret = etcd_mkdir(etcdpath, 0);
        if (unlikely(ret)) {
                if (ret != EEXIST)
                        GOTO(err_ret, ret);
        }

        sprintf(idstr, CHKID_FORMAT, CHKID_ARG(volid));
        ret = etcd_create_text(etcdpath, idstr, idstr, 0);
        if (unlikely(ret)) {
                DWARN("cleanup offline msg %s/%s ret %d\n", etcdpath, idstr, ret);
                if (ret != EEXIST) {
                        GOTO(err_ret, ret);
                }
        }

        return 0;
err_ret:
        return ret;
}

int offline_msg_rm(const nid_t *nid, volid_t *volid)
{
        int ret;
        char etcdpath[MAX_NAME_LEN];

        sprintf(etcdpath, "%s/%d", ETCD_CLEANUP, nid->id);
        ret = etcd_del(etcdpath, id2str(volid));
        if (unlikely(ret))
                GOTO(err_ret, ret);

        return 0;
err_ret:
        return ret;
}

int offline_msg_iterator(const nid_t *nid, func_int1_t func, void *arg)
{
        int ret, i;
        char etcdpath[MAX_NAME_LEN];
        etcd_node_t *list = NULL, *node;

        sprintf(etcdpath, "%s/%d", ETCD_CLEANUP, nid->id);
        ret = etcd_list(etcdpath, &list);
        if (unlikely(ret)) {
                GOTO(err_ret, ret);
        }

        for (i = 0; i < list->num_node; i++) {
                node = list->nodes[i];
                ret = func(node->key, arg);
                if (unlikely(ret))
                        GOTO(err_free, ret);
        }

        free_etcd_node(list);

        return 0;
err_free:
        free_etcd_node(list);
err_ret:
        return ret;
}
